package NewTmas.Listeners;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 7/13/11
 * Time: 10:48 AM
 * To get the existing windows to tile on the desktopPane
 */
public class TileWindowStateListener implements ItemListener {
    JDesktopPane dtp;
    JCheckBoxMenuItem tile;

    public TileWindowStateListener(JDesktopPane dtp, JCheckBoxMenuItem tile) {
        this.dtp=dtp;
        this.tile=tile;
    }

    public void itemStateChanged(ItemEvent e)

    {

        if(tile.isSelected())

            tile(dtp);




    }

    private  void tile( JDesktopPane desktopPane ) {
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if ( frames.length == 0) return;

        tile( frames, desktopPane.getBounds() );
    }


    private void tile( JInternalFrame[] frames, Rectangle dBounds ) {
        int cols = (int)Math.sqrt(frames.length);
        int rows = (int)(Math.ceil( ((double)frames.length) / cols));
        int lastRow = frames.length - cols*(rows-1);
        int width, height;

        if ( lastRow == 0 ) {
            rows--;
            height = dBounds.height / rows;
        }
        else {
            height = dBounds.height / rows;
            if ( lastRow < cols ) {
                rows--;
                width = dBounds.width / lastRow;
                for (int i = 0; i < lastRow; i++ ) {
                    frames[cols*rows+i].setBounds( i*width, rows*height,
                            width, height );
                }
            }
        }

        width = dBounds.width/cols;
        for (int j = 0; j < rows; j++ ) {
            for (int i = 0; i < cols; i++ ) {
                frames[i+j*cols].setBounds( i*width, j*height,
                        frames[i].getWidth(), frames[i].getHeight() );
            }
        }
    }
}
